﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if NETFRAMEWORK
using Fiddler;

namespace PddHelper.Framework
{
    internal class DaiLiHelper
    {
        static int port = 10091;
        static FiddlerCoreStartupSettings settings = new FiddlerCoreStartupSettingsBuilder().RegisterAsSystemProxy().DecryptSSL().ListenOnPort((ushort)port).Build();

        /// <summary>
        /// 微信解析后 回调事件
        /// </summary>
        /// <param name="html"></param>
        internal delegate void BeforeResponse(string html);
        // 定义事件
        internal event BeforeResponse OnBeforeResponse;

        internal DaiLiHelper()
        {
            port = new Random().Next(10000, 20000);
        }

        /// <summary>
        /// 启动代理
        /// </summary>
        internal void Register()
        {
            if (!CertMaker.rootCertExists())
            {
                // 创建根证书并添加到受信任的根证书存储中
                if (CertMaker.createRootCert())
                {
                    CertMaker.trustRootCert();
                }
            }
        }

        internal void Start()
        {
            FiddlerApplication.Startup(settings);
            // 注册 BeforeResponse 事件
            FiddlerApplication.BeforeResponse += FiddlerApplication_BeforeResponse;
        }

        /// <summary>
        /// 关闭代理
        /// </summary>
        internal void Stop()
        {
            FiddlerApplication.Shutdown();
        }

        private void FiddlerApplication_BeforeResponse(Session oSession)
        {
            // 获取请求返回的数据
            var sessionString = oSession.GetResponseBodyAsString();

            //Console.WriteLine(oSession.fullUrl);
            //Tools.FileWrite("d:\\url.txt", oSession.fullUrl + "\n", true);
            if (oSession.fullUrl.Contains("/goods.html?goods_id="))
            {
                var html = oSession.GetResponseBodyAsString();
                //Tools.FileWrite("d:\\1.txt", html, true);
                OnBeforeResponse(html);
            }
        }
    }
}
#endif